route.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { NextResponse } from "next/server";
  2. import automation from "data/automation.json";
  3. const get = (url) => {
  4. console.log("get", url);
  5. return fetch(url, { cache: "no-store" })
  6. .then((resp) => resp && resp.text())
  7. .then((result) => result);
  8. };
  9. const update = ({ id, client, on, bri, ...rest }) => {
  10. let url = `http://${client}/win`;
  11. if (id) url += `&PL=${id}`;
  12. if (on) url += `&T=1`;
  13. else url += `&T=0`;
  14. if (bri) url += `&A=${bri}`;
  15. return get(url)
  16. .then((resp) => ({
  17. ps: id,
  18. on: on,
  19. bri: bri
  20. }))
  21. .catch((err) => ({ error: err.message }));
  22. };
  23. export async function GET(req, { params }) {
  24. let promises = [];
  25. let id = params?.id || null;
  26. try {
  27. if (!id) throw new Error("No id specified");
  28. let clients = (automation?.[id] && Object.keys(automation?.[id])) || [];
  29. if (!clients) throw new Error("No clients fowr id", id);
  30. for (let client of clients) {
  31. promises.push(update({ id, client, ...automation?.[id]?.[client] }));
  32. }
  33. } catch (err) {
  34. return NextResponse.json({ error: err?.message }, { status: 500 });
  35. }
  36. return Promise.allSettled(promises)
  37. .then((results) => {
  38. return NextResponse.json(results?.map((o) => o?.value));
  39. })
  40. .catch((err) => {
  41. return NextResponse.json({ error: err?.message }, { status: 500 });
  42. });
  43. }